<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { Column, Pagination } from '../../types/ant'
import type { FormData, OverTimeItem } from '../../types/attendance'
import { OVERTIME_COLUMNS } from '../../columns'
import { downloadExcel } from '../../utils/excel'

const props = withDefaults(
  defineProps<{
    overTimeList?: OverTimeItem[]
    employeeList?: string[]
  }>(),
  {
    overTimeList: () => [],
    employeeList: () => [],
  },
)

// 表单参数
const formData = ref<FormData> ({
  employeeName: '',
})

// 表格
const page = ref<number>(1)
const list = ref<OverTimeItem[]>([])

watch(
  () => props.overTimeList,
  (val) => {
    list.value = val
  },
  {
    immediate: true,
  },
)

// 查询
function onSearch() {
  page.value = 1
  list.value = !formData.value.employeeName
    ? props.overTimeList
    : props.overTimeList.filter((item: OverTimeItem) => item.employeeName.includes(formData.value.employeeName))
}

// 重置
function onReset() {
  formData.value.employeeName = ''
  onSearch()
}

// 切换分页
function onChangeList(pagination: Pagination) {
  page.value = pagination.current
}

// 导出EXCEL
function onDownload() {
  // 数据格式处理
  const data = list.value.map((item: OverTimeItem) => {
    const sheet: Record<string, any> = {}
    OVERTIME_COLUMNS.forEach((column: Column) => {
      sheet[column.title] = item[column.key as keyof OverTimeItem]
    })
    return sheet
  })
  // 导出
  downloadExcel(data, '加班数据统计')
}
</script>

<template>
  <div class="filter-conatiner">
    <a-form layout="inline">
      <a-form-item label="员工姓名">
        <a-select
          v-model:value="formData.employeeName"
          allow-clear
          show-search
        >
          <a-select-option
            v-for="item in employeeList"
            :key="item"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>

    <div class="action">
      <a-button type="primary" @click="onSearch">
        查询
      </a-button>
      <a-button @click="onReset">
        重置
      </a-button>
      <a-button type="primary" @click="onDownload">
        导出EXCEL
      </a-button>
    </div>
  </div>

  <div class="table-container">
    <a-table
      :columns="OVERTIME_COLUMNS"
      :data-source="list"
      :pagination="{
        current: page,
      }"
      @change="onChangeList"
    />
  </div>
</template>

<style lang="scss" scoped>
.filter-conatiner {
  display: flex;
  align-items: center;
  margin: 8px 0 24px;

  .ant-select {
    width: 200px;
  }
}
</style>
